package com.beordie.control;

import com.beordie.model.Menu;
import com.beordie.model.Role;
import com.beordie.model.Users;
import com.beordie.service.IRoleService;
import com.beordie.service.IUsersService;
import com.beordie.service.impl.RoleServiceImpl;
import com.beordie.service.impl.UsersServiceImpl;
import com.beordie.utils.PageUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname UserController
 * @Description 管理员相关请求的处理类
 * @Date 2021/6/8 12:49
 * @Created 30500
 */
@WebServlet(urlPatterns = {"/power/user/users","/login"})
public class UserController extends HttpServlet {
    private IUsersService service = new UsersServiceImpl();
    private IRoleService roleService = new RoleServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
        // 反射分发消息到对应的处理方法
        String methodString = req.getParameter("method");

        try {
            // 取出对应的方法
            Method method = this.getClass().getDeclaredMethod(methodString, HttpServletRequest.class, HttpServletResponse.class);
            try {
                method.invoke(this, req, resp);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

    }

    /**
     * @description 登陆请求
     * @author 30500
     * @date 2021/6/16 22:33
     * @type [javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse]
     * @return void
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 拿到前端返回的数据信息
        String loginName = req.getParameter("UserName");
        String password = req.getParameter("Password");
        Users user = service.getByNamePassword(loginName, password);
        List<Menu> list = user.getRole().getMenu();
        if (user != null){
            req.getSession().setAttribute("user", user);
            resp.sendRedirect("index.jsp");
        } else {
            resp.sendRedirect("login.jsp");
        }
    }

    /**
     * @description 退出登陆请求
     * @author 30500
     * @date 2021/6/16 22:33
     * @type [javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse]
     * @return void
     */
    protected void quit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().invalidate();
        resp.getWriter().print("<script>top.location.href='login.jsp';alert('确认退出')</script>");
    }

    /**
     * @description 查询所有的管理信息
     * @author 30500
     * @date 2021/6/16 22:33
     * @type [javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse]
     * @return void
     */
    protected void select(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 拿到起始页面页数
        String pageIndex = req.getParameter("index");
        int index = pageIndex == null ? 1 : Integer.parseInt(pageIndex);
        int total = 0;
        PageUtils pageUtils = new PageUtils();

        // 获取数据库的信息数据
        List<Users> users = new ArrayList<>();
        total = service.getByAll();
        users = service.getByLimit(index, pageUtils.getPageSize());

        // 设置页码工具信息
        pageUtils.setPageIndex(index);
        pageUtils.setTotal(total);
        pageUtils.setDataList(users);

        req.setAttribute("pageUtils", pageUtils);
        req.getRequestDispatcher("list.jsp").forward(req, resp);
    }

    /**
     * @description 添加管理员请求
     * @author 30500
     * @date 2021/6/16 22:34
     * @type [javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse]
     * @return void
     */
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String loginName = req.getParameter("loginName");
        String password = req.getParameter("password");
        String name = req.getParameter("name");
        int sex = Integer.parseInt(req.getParameter("sex"));
        String email = req.getParameter("email");
        String address = req.getParameter("address");
        String phone = req.getParameter("phone");
        String number = req.getParameter("number");
        String desc = req.getParameter("desc");
        int roleId = Integer.parseInt(req.getParameter("roleId"));
        Users user = new Users();

        // 填充数据
        user.setLoginName(loginName);
        user.setPassword(password);
        user.setRealName(name);
        user.setSex(sex);
        user.setEmail(email);
        user.setAddress(address);
        user.setPhone(phone);
        user.setCardId(number);
        user.setDescription(desc);
        user.setRoleId(roleId);

        // 数据库响应
        int result = service.add(user);
        if (result > 0) {
            resp.sendRedirect("/power/user/users?method=select");
        } else {
            req.setAttribute("user", user);
            req.getRequestDispatcher("/power/role/roles?method=transitionAdd").forward(req, resp);
        }
    }

    /**
     * @description 更新数据携带跳转
     * @author 30500
     * @date 2021/6/17 23:14
     * @type [javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse]
     * @return void
     */
    protected void transitionUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int userId = Integer.parseInt(req.getParameter("userId"));

        // 拿到数据库的信息
        Users user = service.getByIndex(userId);
        List<Role> roles = roleService.getAll();

        req.setAttribute("roles", roles);
        req.setAttribute("user", user);
        req.getRequestDispatcher("edit.jsp").forward(req, resp);
    }

    /**
     * @description 删除一条管理员信息
     * @author 30500
     * @date 2021/6/19 12:28
     * @type [javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse]
     * @return void
     */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int userId = Integer.parseInt(req.getParameter("userId"));
        int result = service.delete(userId);

        if (result > 0) {
            resp.getWriter().print("<script>alert('删除成功');location.href='/power/user/users?method=select'</script>");
        } else {
            resp.getWriter().print("<script>alert('删除失败');location.href='/power/user/users?method=select'</script>");
        }
    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int userId = Integer.parseInt(req.getParameter("userId"));
        String loginName = req.getParameter("loginName");
        String password = req.getParameter("password");
        String name = req.getParameter("name");
        int sex = Integer.parseInt(req.getParameter("sex"));
        String email = req.getParameter("email");
        String address = req.getParameter("address");
        String phone = req.getParameter("phone");
        String number = req.getParameter("number");
        String desc = req.getParameter("desc");
        int roleId = Integer.parseInt(req.getParameter("roleId"));
        Users user = new Users();

        // 填充数据
        user.setUserId(userId);
        user.setLoginName(loginName);
        user.setPassword(password);
        user.setRealName(name);
        user.setSex(sex);
        user.setEmail(email);
        user.setAddress(address);
        user.setPhone(phone);
        user.setCardId(number);
        user.setDescription(desc);
        user.setRoleId(roleId);

        // 数据库响应
        int result = service.update(user);
        if (result > 0) {
            resp.sendRedirect("/power/user/users?method=select");
        } else {
            req.setAttribute("user", user);
            req.getRequestDispatcher("edit.jsp").forward(req, resp);
        }
    }
}
